package jsf;

import java.io.IOException;
import java.io.Serializable;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

import ejb.UsersBeanRemote;
import entity.Users;
import util.SessionUtil;

@RequestScoped
@ManagedBean
public class LoginController implements Serializable {

	private static final long serialVersionUID = 1L;
	@EJB(lookup="java:global/EnrollmentManagementEAP/EnrollmentManagementEJB/UsersBean!ejb.UsersBeanRemote")
	UsersBeanRemote userBean;
	private String errorMsg;
	private String username;
	private String password;

	public String getErrorMsg() {
		return errorMsg;
	}
	
	public String getUsername() {
		return username;
	}
	
	public void setUsername(String username) {
		this.username = username;
	}
	
	public String getPassword() {
		return password;
	}
	
	public void setPassword(String password) {
		this.password = password;
	}
	
	public void doLogin() {
		Users user = userBean.authenticate(username, password);

		if(user != null) {
			SessionUtil.set("user", user.getId());
			ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
			try {
				context.redirect("home.xhtml");
			} catch (IOException e) {}
		} else {
			this.errorMsg = "Login failed.";
		}
	}
	
	public void doLogout() {
		SessionUtil.set("user", null);
		ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
		try {
			context.redirect("login.xhtml");
		} catch (IOException e) {}
	}
}
